package com.yn.iotxiao.Utils;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;


@Slf4j
@Data
public class HikHttpUtil {

    private String ip;
    private String uri;
    private String url;
    private CloseableHttpClient httpClient;

    public HikHttpUtil(String ip, String uri, String loginId, String password) {
        this.ip = ip;
        this.url = "http://" + ip + uri + "?format=json";

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(loginId, password);
        credsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
        this.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    }
    public HikHttpUtil(String ip, String uri, String loginId, String password, Boolean isXml) {
        this.ip = ip;
        this.url = "http://" + ip + uri ;

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(loginId, password);
        credsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
        this.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    }
    /**
     * get请求
     *
     * @return
     * @throws Exception
     */
    public String doGet() throws Exception {

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse responseBody = this.httpClient.execute(httpGet);
        HttpEntity responseEntity = responseBody.getEntity();
        if (responseEntity != null) {
            String response = EntityUtils.toString(responseEntity);
            return response;
        }
        return null;
    }

    /**
     * delete请求
     *
     * @return
     * @throws Exception
     */
    public String doDelete() throws Exception {

        HttpDelete httpDelete = new HttpDelete(url);
        CloseableHttpResponse responseBody = this.httpClient.execute(httpDelete);
        HttpEntity responseEntity = responseBody.getEntity();
        if (responseEntity != null) {
            String response = EntityUtils.toString(responseEntity);
            return response;
        }
        return null;
    }

    /**
     * body方式发起post请求
     *
     * @return
     * @throws Exception
     */
    public String doBodyPost(JSONObject body) throws Exception {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(body.toString(), "UTF-8"));
        CloseableHttpResponse responseBody = this.httpClient.execute(httpPost);
        HttpEntity responseEntity = responseBody.getEntity();
        if (responseEntity != null) {
            String response = EntityUtils.toString(responseEntity);
            return response;
        }
        return null;
    }


    /**
     * body方式发起post请求
     *
     * @return
     * @throws Exception
     */
    public JSONObject doBodyPut(JSONObject body) throws Exception {

        log.error("url:" + url);
        HttpPut HttpPut = new HttpPut(url);
        HttpPut.setEntity(new StringEntity(body.toString(), "UTF-8"));
        CloseableHttpResponse responseBody = httpClient.execute(HttpPut);
        HttpEntity responseEntity = responseBody.getEntity();
        if (responseEntity != null) {
            String response = EntityUtils.toString(responseEntity);
            if (response.contains("<?xml version=")) {
                return XMLParse.xml2Json(response);
            }
            return JSON.parseObject(response);
        }
        return null;
    }

    public JSONObject doPut(String body) throws Exception {

        HttpPut HttpPut = new HttpPut(url);
        HttpPut.setEntity(new StringEntity(body, "UTF-8"));
        CloseableHttpResponse responseBody = httpClient.execute(HttpPut);
        HttpEntity responseEntity = responseBody.getEntity();
        if (responseEntity != null) {
            String response = EntityUtils.toString(responseEntity);
            if (response.contains("<?xml version=")) {
                return XMLParse.xml2Json(response);
            }
            return JSON.parseObject(response);
        }
        return null;
    }

    /**
     * 以表单方式发起 post 请求
     * @param config
     * @return
     * @throws Exception
     */
//    public String doFormDataPost(FormRequestConfig config) throws Exception {
//        CredentialsProvider credsProvider = new BasicCredentialsProvider();
//        AuthScope favourite_digest_realm = new AuthScope(config.getIp(), config.getPort());
//        UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(config.getUsername(), config.getPassword());
//        credsProvider.setCredentials(favourite_digest_realm,usernamePasswordCredentials);
//        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
//        HttpPost httpPost = new HttpPost(config.getAgreement()+"://"+config.getIp()+":"+config.getPort()+config.getUri());
//        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//        config.getFormData().forEach((k,v)->{
//            builder.addPart(k,new StringBody(v, ContentType.create(config.getType(), Consts.UTF_8)));
//        });
//        if (config.getFile()!=null){
//            if (!config.getFile().exists()){
//                throw new FileNotFoundException("文件不存在！"+config.getFile().getAbsolutePath());
//            }
//            builder.addBinaryBody(config.getFileName(),config.getFile(),ContentType.create("image/jpeg"),config.getFile().getName());
//        }
//        HttpEntity reqEntity = builder.build();
//        httpPost.setEntity(reqEntity);
//        CloseableHttpResponse responseBody = httpclient.execute(httpPost);
//        HttpEntity responseEntity = responseBody.getEntity();
//        if (responseEntity != null) {
//            String response = EntityUtils.toString(responseEntity);
//            return response;
//        }
//        return null;
//    }
//
//    /**
//     * 表单方式发起 put 请求
//     * @param config
//     * @return
//     * @throws Exception
//     */
    public String doFormDataPut(JSONObject body, MultipartFile file) throws Exception {


        HttpPut httpPut = new HttpPut(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        body.forEach((k,v)->{
            builder.addPart(k,new StringBody(v.toString(), ContentType.create("text/json", Consts.UTF_8)));
        });
        if (file !=null) {
            builder.addBinaryBody(file.getName(),file.getBytes(),ContentType.create("image/jpeg"),file.getName());
        }
        HttpEntity reqEntity = builder.build();
        httpPut.setEntity(reqEntity);
        CloseableHttpResponse responseBody = httpClient.execute(httpPut);
        HttpEntity responseEntity = responseBody.getEntity();
        if (responseEntity != null) {
            String response = EntityUtils.toString(responseEntity);
            return response;
        }
        return null;
    }

    /**
     * 导入人脸数据
     * @param body  人脸信息
     * @param file 人脸图片
     * @return
     * @throws Exception
     */
    public String importImage(JSONObject body, MultipartFile file) throws Exception {


        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        body.forEach((k,v)->{
            builder.addPart(k,new StringBody(v.toString(), ContentType.create("text/json", Consts.UTF_8)));
        });
        if (file !=null) {
            builder.addBinaryBody("importImage",file.getBytes(),ContentType.create("image/jpeg"),file.getName());
        }

        HttpEntity reqEntity = builder.build();
        httpPost.setEntity(reqEntity);
        CloseableHttpResponse responseBody = httpClient.execute(httpPost);
        HttpEntity responseEntity = responseBody.getEntity();
        if (responseEntity != null) {
            String response = EntityUtils.toString(responseEntity);
            return response;
        }
        return null;
    }
}
